const conversationDao = require('../dao/conversationDao')
const userDao = require('../dao/userDao')

// 添加
exports.add = async ctx => {
  let body = ctx.request.body;
  let { sender,receiverId } = body
  // 发送者信息
  const senderInfo = await userDao.findById({id:sender})
  const receiverInfo = await userDao.findById({id:receiverId})
  // 两条信息
  let senderBody = {
    sender:senderInfo.id,
    receiverName: receiverInfo.username,
    receiverId: receiverInfo.id,
    receiverSocketID:receiverInfo.socketID,
    receiverImg: receiverInfo.avatar
  }
  let receiverBody = {
    sender:receiverInfo.id,
    receiverName: senderInfo.username,
    receiverId: senderInfo.id,
    receiverSocketID:senderInfo.socketID,
    receiverImg: senderInfo.avatar
  }
  // 查找是否已添加
  const res = await conversationDao.getOneByReceiverId(senderBody)
  if(!res){
    console.log(res);
    await conversationDao.create(senderBody);
    await conversationDao.create(receiverBody);
    ctx.success('创建成功')
  } else {
    ctx.success('tips:已添加')
  }
}

// 获取全部
exports.getAll = async ctx => {
  let { p = 1,limit = 999 } = ctx.request.query
  let offset = (p - 1) * limit;
  let body = {
    offset:offset,
    limit:Number(limit)
  }
  const res = await conversationDao.findAll(body);
  ctx.success('',res)
}

// 删除某条数据
exports.del = async ctx => {
  let { id } = ctx.request.query
  const res = await conversationDao.delById(id);
  ctx.success('删除成功')
}

// 修改某条数据
exports.upd = async ctx => {
  let body = ctx.request.body
  const res = await conversationDao.upd(body);
  ctx.success('修改成功')
}


// 获取某用户的数据
exports.getSomebody = async ctx => {
  let { id } = ctx.request.query  
  const res = await conversationDao.getSBList(id);
  ctx.success('获取成功',res)
}
